<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/10/26
 * Time: 09:59
 */

namespace Modules\Admin\Service;

use HiCommon\Repository\ExpressRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\StoreOrderRefundRepository;
use HiCommon\Service\PayService;

class StoreOrderService
{
    /**
     * 获取所有权限
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_all()
    {
        try {
            $arr_option = ['order' => ['key' => 'id', 'value' => 'asc']];
            $data = StoreOrderRepository::get_all($arr_option)->toarray();
            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 筛选条件处理
     */
    public function search_handle($arr_search=[])
    {
        $where['shop_id'] = get_shop_id();//门店id
        if (!empty($arr_search['order_type'])) {
            $where['order_type'] = $arr_search['order_type'];
        }

        if (!empty($arr_search['order_no'])) {
            $where['order_no'] = $arr_search['order_no'];
        }

        if (!empty($arr_search['range'])) {
            $where['range'] = $arr_search['range'];
        }

        if (!empty($arr_search['status'])) {
            $where['status'] = $arr_search['status'];
            if ($arr_search['status'] == 100) {
                $where['status'] = 1;
                $where['pay_status'] = 1;
            } elseif ($arr_search['status'] == 200) {
                $where['status'] = 1;
                $where['pay_status'] = 2;
            } elseif ($arr_search['status'] == 300) {
                $where['status'] = 7;
            } elseif ($arr_search['status'] == 400) {
                $where['status'] = 9;
            }
        }

        return $where;
    }
    /**
     * 获取分页数据
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($arr_search)
    {
        try {
            //筛选条件
            $where = self::search_handle($arr_search);

            $arr_option['where'] = $where;
            $arr_option['with'] = ['getOrderGoods', 'order_refund'];
            $data = StoreOrderRepository::get_list($arr_option);
            $data->appends($arr_search);//添加链接参数
            $data = list_page_data($data, $arr_search);
            foreach ($data['data'] as $key => &$value) {
                $value['order_status'] = StoreOrderRepository::order_status($value['status'], $value['pay_status']);
            }
            $shop_id = $where['shop_id'];
            $data['d_num'] = StoreOrderRepository::get_count_by_where(['status' => 1, 'pay_status' => 2, 'shop_id' => $shop_id]);//待发货订单数量
            //$data['t_num'] = StoreOrderRepository::get_count_by_where(['status' => 6, 'pay_status' => 2, 'shop_id' => $shop_id]);//申请退款订单数量
            //$data['r_num'] = StoreOrderRepository::get_count_by_where(['status' => 8, 'pay_status' => 2, 'shop_id' => $shop_id]);//申请退货订单数量

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 查询一条数据
     *
     * @param int $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one(int $n_id)
    {
        try {
            $n_id = (int)$n_id;
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }

            //查询
            $arr_option['with'] = ['getUser', 'getOrderGoods', 'getAddress', 'getExpress', 'order_refund', 'get_cancel_reason'];
            $res = StoreOrderRepository::get_one($n_id, $arr_option)->toarray();
            $res['xpress'] = ExpressRepository::get_all()->toArray();//快递公司列表
            $res['order_state'] = StoreOrderRepository::order_status($res['status'], $res['pay_status']);
            if (!empty($res['order_refund']['picture'])) {
                $picture = json_decode($res['order_refund']['picture']);
                foreach ($picture as $key => $value) {
                    $res['order_refund']['pics'][] = oss_full_url($value);
                }
            }
            if (empty($res)) {
                return hello_error('查询失败');
            }

            return hello_success('查询成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = StoreOrderRepository::delete_one($n_id);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 快速发货
     * 2019 11 09
     */
    public function sendGoods($arr_input)
    {
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('订单id不能为空');
            }
            $map = ['id' => (int)$arr_input['id']];
            $up_data = [
                'xpress_id' => (int)$arr_input['xpress_id'],
                'delivery_no' => $arr_input['delivery_no'],
                'delivery_time' => date('Y-m-d H:i:s'),
                'status' => 2
            ];

            $res = StoreOrderRepository::edit_one($map, $up_data);
            if ($res === false) {
                return hello_error('操作失败');
            }

            return hello_success('操作成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    //获取订单列表（导出Excel）
    public function get_order_list($arr_search)
    {
        try {
            $arr_option['where'] = self::search_handle($arr_search);
            $arr_option['with'] = ['getUser', 'getOrderGoods', 'getAddress', 'getExpress', 'order_refund'];
            $data = StoreOrderRepository::get_all($arr_option)->toArray();
            foreach ($data as $key => &$value) {
                $value['order_status'] = StoreOrderRepository::order_status($value['status'], $value['pay_status']);
            }

            return $data;
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     * 修改单个字段
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function changStatus($arr_input)
    {
        try {
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }
            $order_id = (int)$arr_input['id'];
            $status = (int)$arr_input['status'];
            $user_coupon_id = (int)$arr_input['user_coupon_id'];

            if ($status == 2) { //修改订单为已支付
                $up_data = [
                    'pay_status' => 2,
                    'pay_time' => date('Y-m-d H:i:s'),
                    'outer_trade_no' => 'hou-tai-zhi-fu'
                ];
                StoreOrderRepository::edit_one((array)['id' => $order_id], (array)$up_data);

                return hello_success('支付成功');
            }

            if ($status == 5) { //取消订单并回收库存
                $up_data = [
                    'status' => 5,
                    'order_status' => 5,
                    'cancel_time' => date('Y-m-d H:i:s', time()),
                    'cancel_reason_id' => 0
                ];
                StoreOrderRepository::edit_one((array)['id' => $order_id], (array)$up_data);//取消订单

                StoreOrderRepository::cancelOrderBackStock((int)$order_id, $user_coupon_id);//回收库存

                return hello_success('取消成功');

            } elseif ($status == 7 || $status == 9) {

                // 退款退货操作
                return self::refund_amount($order_id);

            } else {
                return hello_error('所传状态有误');
            }

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 计算退款金额（更新订单状态）
     */
    public function refund_amount($order_id)
    {
        $arr_option['with'] = ['get_refund_price', 'order_refund'];
        $arr_option['field'] = ['id', 'order_no', 'outer_trade_no', 'user_id', 'status', 'pay_type', 'pay_amount', 'delivery_price'];
        $order = StoreOrderRepository::get_one($order_id, $arr_option)->toarray();

        $refund_amount = 0.00;
        if (!empty($order['get_refund_price']) && !empty($order['order_refund'])) {
            foreach ($order['get_refund_price'] as $key => $value) {
                if ($value['is_refund'] == 1) {
                    //退款总额
                    $refund_amount += $value['refund_price'];
                    if ($order['order_refund']['apply_type'] == 3) {
                        //仅在退回货物后回收库存
                        GoodsProductRepository::increase_num($value['goods_product_id'], 'stock', $value['goods_num']);
                    }
                }
            }
        }

        $up_data = [];
        if ($order['status'] == 6) { //退款
            $up_data = ['status' => 7, 'refund_price' => $refund_amount];
        }

        if ($order['status'] == 8 && !empty($order['get_refund_price'])) { //退货
            $up_data = ['status' => 9, 'refund_price' => $refund_amount];
        }

        //更新订单状态
        StoreOrderRepository::edit_one(['id' => $order_id], (array)$up_data);

        $up_array = [
            'apply_state' => 2,
            'refund_amount' => $refund_amount,
            'deal_at' => date('Y-m-d H:i:s')
        ];

        //更新退单状态
        StoreOrderRefundRepository::edit_one_by_where(['store_order_id' => $order_id], (array)$up_array);
        return hello_success('成功');
        /*if ($order['pay_type'] == 1) {//退回微信
            //退款操作
            $s_refund_type = 'wechat_app_pay';
            $s_order_sn = $order['order_no'];
            $s_out_trade_no = $order['outer_trade_no'];
            $n_total_fee = intval($refund_amount * 100);
            $n_refund_fee = $n_total_fee;
            $arr_option = ['refund_desc' => '订单退款'];

            return PayService::refund($s_refund_type, $s_order_sn, $s_out_trade_no, $n_total_fee, $n_refund_fee, $arr_option);

        } else {//退回支付宝

        }*/
    }



}